#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

class MyString
{
public:
    MyString();
    MyString(const char *str);
    MyString(const MyString &str);
    MyString& operator=(const MyString &str);
    ~MyString();

    void display();

private:
    char *m_data;
    int m_length;
};

MyString::MyString()
{
    cout << "MyString()" << endl;
    m_data = NULL;
    m_length = 0;
}
MyString::MyString(const char *str)
{
    cout << "MyString(const char *str)" << endl;
    m_length = strlen(str);
    m_data = new char[m_length+1];
    strcpy(m_data, str);
}

MyString::MyString(const MyString &str)
{
    cout << "MyString::MyString(const MyString &str)" << endl;
    this->m_length = str.m_length;
    this->m_data = new char[m_length+1];
    strcpy(m_data, str.m_data);
}

MyString::~MyString()
{
    cout << "~MyString()" << endl;
    if(m_data) delete []m_data;
}

void MyString::display()
{
    if(m_data) cout << m_data << endl;
    else cout << "-" << endl;
}

MyString& MyString::operator=(const MyString &str)
{
    cout << "MyString& MyString::operator=(const MyString &str)" << endl;
    if(this == &str) return *this;

    if(this->m_length < str.m_length)
    {
        if(this->m_data) delete []this->m_data;
        this->m_data = new char[str.m_length+1];
    }

    strcpy(this->m_data, str.m_data);
    this->m_length = str.m_length;
    return *this;
}

MyString func(const MyString &str)
{
    MyString str2("---------");
    str2 = str;
    return str;
}

int main()
{
    MyString one, two;
    one += two;

    MyString str("hello");      /// int a(5);
    str.display();

    MyString str1 = func(str);

//    MyString str_1 = str;       /// int b = a;  --拷贝构造函数
//    str_1.display();
//
//    MyString str_2("world");    /// int c = 10;
//    str_2.display();
//
////    str_2 = str;                /// c = a;      --赋值函数
//    str_2.operator=(str);         /// a = b = c = d;
//    str_2.display();

    return 0;
}

